package cn.springcloud.fix.oauth.config;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证服务器配置
 * https://blog.csdn.net/andy_zhang2007/article/details/84726992
 */
@Slf4j
@Configuration
@AllArgsConstructor
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private final AuthenticationManager authenticationManager;
    private final RedisConnectionFactory redisConnectionFactory;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("app1")
                .secret("{bcrypt}$2a$10$NsTKjoAo/Dvf0SWXrisx4OLt9ra8iMcZNJI9MUJzWhYvCEGpBCD5i") // 123456
                .authorizedGrantTypes("authorization_code", "refresh_token")
                .redirectUris("http://localhost:8082/client1/login")
                .scopes("all")
                .autoApprove(true)
                .and()
                .withClient("app2")
                .secret("{bcrypt}$2a$10$NsTKjoAo/Dvf0SWXrisx4OLt9ra8iMcZNJI9MUJzWhYvCEGpBCD5i") // 123456
                .authorizedGrantTypes("password", "refresh_token")
                // .redirectUris("http://localhost:8082/user/info")
                .autoApprove(true)
                .scopes("all");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
                .authenticationManager(authenticationManager)
                .tokenStore(new RedisTokenStore(redisConnectionFactory))
                .tokenEnhancer(tokenEnhancer())
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()")
                .allowFormAuthenticationForClients()
        ;
    }

    /**
     * token增强，客户端模式不增强。
     */
    @Bean
    public TokenEnhancer tokenEnhancer() {
        return (accessToken, authentication) -> {
            if ("client_credentials".equals(authentication.getOAuth2Request().getGrantType())) {
                return accessToken; // 客户端模式不增强
            }
            Object principal = authentication.getUserAuthentication().getPrincipal();
            Map<String, Object> additionalInfo = new HashMap<>(8);
            additionalInfo.put("userId", 19);
            // PigxUser pigxUser = (PigxUser) authentication.getUserAuthentication().getPrincipal();
            // additionalInfo.put(SecurityConstants.DETAILS_USER_ID, pigxUser.getId());
            // additionalInfo.put(SecurityConstants.DETAILS_USERNAME, pigxUser.getUsername());
            // additionalInfo.put(SecurityConstants.DETAILS_DEPT_ID, pigxUser.getDeptId());
            // additionalInfo.put(SecurityConstants.DETAILS_TENANT_ID, pigxUser.getTenantId());
            // additionalInfo.put(SecurityConstants.DETAILS_LICENSE, SecurityConstants.PIGX_LICENSE);
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
            return accessToken;
        };
    }
}
